package com.qiantu.phone.ui.fragment;

import static android.app.Activity.RESULT_OK;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemLongClickListener;
import com.hjq.base.BaseAdapter;
import com.hjq.http.listener.HttpCallback;
import com.hjq.toast.ToastUtils;
import com.hjq.umeng.UmengClient;
import com.hjq.widget.view.SwitchButton;
import com.qiantu.api.db.LLDeviceDBManager;
import com.qiantu.api.db.LLFloorDBManager;
import com.qiantu.api.db.LLRoomDBManager;
import com.qiantu.api.db.LLSceneDBManager;
import com.qiantu.api.db.LLSourceHomepageDBManager;
import com.qiantu.api.entity.DeviceBean;
import com.qiantu.api.entity.FloorBean;
import com.qiantu.api.entity.LinkageBean;
import com.qiantu.api.entity.RoomBean;
import com.qiantu.api.entity.SceneBean;
import com.qiantu.api.entity.SourceHomepageBean;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.app.AppFragment;
import com.qiantu.phone.event.RefreshRoomDeviceEvent;
import com.qiantu.phone.ui.activity.AddRoomActivity;
import com.qiantu.phone.ui.activity.FloorSettingActivity;
import com.qiantu.phone.ui.activity.RoomDeviceActivity;
import com.qiantu.phone.ui.activity.RoomLinkageActivity;
import com.qiantu.phone.ui.activity.RoomSettingActivity;
import com.qiantu.phone.ui.adapter.RoomListBigAdapter;
import com.qiantu.phone.ui.adapter.RoomListSmallAdapter;
import com.qiantu.phone.ui.uiutil.LLDeviceUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;

public class RoomListFragment extends AppFragment<AppActivity> {
    private static final int EDIT_ROOM_CODE = 777;
    private int showType = 1;
    private String floorSerialNo;
    private RecyclerView roomRecyclerView;
    private RecyclerView roomSmallRecyclerView;
    private int pageIndex = 1;
    private int pageSize = Integer.MAX_VALUE;
    //0全部、1时间变化、2环境变化、4设备变化
    private RoomListBigAdapter mRoomListBigAdapter;
    //0全部、1时间变化、2环境变化、4设备变化
    private RoomListSmallAdapter mRoomListSmallAdapter;
    public List<RoomBean> rooms;
    private LinearLayout ll_Noequipment;
    private TextView btn;

    public static RoomListFragment newInstance(String floorSerialNo, int type) {
        RoomListFragment fragment = new RoomListFragment();
        Bundle bundle = new Bundle();
        bundle.putString("floorSerialNo",floorSerialNo);
        fragment.setShowType(type);
        fragment.setArguments(bundle);
        return fragment;
    }

    public int getShowType() {
        return showType;
    }

    public void setShowType(int showType) {
        this.showType = showType;
    }

    public String getFloorSerialNo() {
        return floorSerialNo;
    }
    @Override
    protected int getLayoutId() {
        return R.layout.fragment_room_list;
    }

    @Override
    protected void initView() {
        floorSerialNo = getString("floorSerialNo");
        EventBus.getDefault().register(this);
        ll_Noequipment = findViewById(R.id.ll_Noequipment);
        btn = findViewById(R.id.btn);
        roomRecyclerView = findViewById(R.id.room_recycler_view);
        roomSmallRecyclerView = findViewById(R.id.room_small_recycler_view);
        if(AppApplication.getInstance().getCurHouseInfo().getRoleType() == 2){
            btn.setVisibility(View.GONE);
        }
        initRecyclerView();
    }

    private void initRecyclerView() {
        roomRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mRoomListBigAdapter = new RoomListBigAdapter(getContext());
        roomRecyclerView.setAdapter(mRoomListBigAdapter);
        mRoomListBigAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
                RoomBean roomBean = mRoomListBigAdapter.getData().get(position);
                if(roomBean.getRoomSerialNo() == null){
                    FloorBean floorBean = LLFloorDBManager.getInstance(getContext()).getFloorByFloorSerialNo(roomBean.getFloorSerialNo());
                    Intent intent = new Intent(getActivity(), RoomDeviceActivity.class);
                    intent.putExtra("type", 2);
                    intent.putExtra("roomSerialNo", floorBean.getFloorSerialNo());
                    intent.putExtra("title", floorBean.getFloorName());
                    startActivity(intent);
                }else{
                    Intent intent = new Intent(getActivity(), RoomDeviceActivity.class);
                    intent.putExtra("type", 0);
                    intent.putExtra("roomSerialNo", roomBean.getRoomSerialNo());
                    intent.putExtra("title", roomBean.getRoomName());
                    startActivity(intent);
                }
            }
        });
        mRoomListBigAdapter.setOnChildClickListener(R.id.btn_setting, new BaseAdapter.OnChildClickListener() {
            @Override
            public void onChildClick(RecyclerView recyclerView, View childView, int position) {
                //特殊处理没有楼层的情况
                RoomBean roomBean = mRoomListBigAdapter.getData().get(position);
                if(roomBean.getRoomSerialNo() == null){
                    FloorBean floorBean = LLFloorDBManager.getInstance(getContext()).getFloorByFloorSerialNo(roomBean.getFloorSerialNo());
                    Intent intent = new Intent(getActivity(), FloorSettingActivity.class);
                    intent.putExtra("floorSerialNo", floorBean.getFloorSerialNo());
                    intent.putExtra("type", 2);
                    startActivity(intent);
                }else{
                    FloorBean floorBean = LLFloorDBManager.getInstance(getContext()).getFloorByFloorSerialNo(floorSerialNo);
                    Intent intent = new Intent(getActivity(), RoomSettingActivity.class);
                    intent.putExtra("floorName", floorBean.getFloorName());
                    intent.putExtra("floorType", floorBean.getType());
                    intent.putExtra("roomName", roomBean.getRoomName());
                    intent.putExtra("roomSerialNo", roomBean.getRoomSerialNo());
                    intent.putExtra("roomSerialNo", roomBean.getRoomSerialNo());
                    intent.putExtra("floorSerialNo", roomBean.getFloorSerialNo());
                    intent.putExtra("roomType",roomBean.getRoomTypeId());
                    intent.putExtra("shareCount",roomBean.getShareCount());
                    startActivity(intent);
                }
            }
        });
        mRoomListBigAdapter.setOnChildClickListener(R.id.btn_close, new BaseAdapter.OnChildClickListener() {
            @Override
            public void onChildClick(RecyclerView recyclerView, View childView, int position) {
                RoomBean roomBean = mRoomListBigAdapter.getData().get(position);
                closeAllDevice(roomBean);
            }
        });

        mRoomListBigAdapter.setOnChildClickListener(R.id.btn_roomLinkage, new BaseAdapter.OnChildClickListener() {
            @Override
            public void onChildClick(RecyclerView recyclerView, View childView, int position) {


                RoomBean roomBean = mRoomListBigAdapter.getData().get(position);
                if(roomBean.getRoomSerialNo() == null){
                    if (position == 0 && roomBean.getRoomName().equals("全屋")){
                        RoomLinkageActivity.start(getContext(),"",0);
                    }else {
                        FloorBean floorBean = LLFloorDBManager.getInstance(getContext()).getFloorByFloorSerialNo(roomBean.getFloorSerialNo());
                        RoomLinkageActivity.start(getContext(),floorBean.getFloorSerialNo(),1);
                    }

                }else{

                    RoomLinkageActivity.start(getContext(),roomBean.getRoomSerialNo(),2);



                }

            }
        });

        GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), 2);
        roomSmallRecyclerView.setLayoutManager(gridLayoutManager);
        mRoomListSmallAdapter = new RoomListSmallAdapter(getContext());
        roomSmallRecyclerView.setAdapter(mRoomListSmallAdapter);
        mRoomListSmallAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
                RoomBean roomBean = mRoomListSmallAdapter.getData().get(position);
                if(roomBean.getRoomSerialNo() == null){
                    FloorBean floorBean = LLFloorDBManager.getInstance(getContext()).getFloorByFloorSerialNo(roomBean.getFloorSerialNo());
                    Intent intent = new Intent(getActivity(), RoomDeviceActivity.class);
                    intent.putExtra("type", 2);
                    intent.putExtra("roomSerialNo", floorBean.getFloorSerialNo());
                    intent.putExtra("title", floorBean.getFloorName());
                    startActivity(intent);
                }else{
                    Intent intent = new Intent(getActivity(), RoomDeviceActivity.class);
                    intent.putExtra("type", 0);
                    intent.putExtra("roomSerialNo", roomBean.getRoomSerialNo());
                    intent.putExtra("title", roomBean.getRoomName());
                    startActivity(intent);
                }
            }
        });
        mRoomListSmallAdapter.setOnChildClickListener(R.id.btn_all_close, new BaseAdapter.OnChildClickListener() {
            @Override
            public void onChildClick(RecyclerView recyclerView, View childView, int position) {
                RoomBean roomBean = mRoomListBigAdapter.getData().get(position);
                closeAllDevice(roomBean);
            }
        });
        setViewShow();
    }

    public void changeShowType(int showType){
        this.showType = showType;
        setViewShow();
    }

    public void setViewShow() {
        if (showType == 0) {
            roomRecyclerView.setVisibility(View.VISIBLE);
            roomSmallRecyclerView.setVisibility(View.GONE);
        } else {
            roomRecyclerView.setVisibility(View.GONE);
            roomSmallRecyclerView.setVisibility(View.VISIBLE);
        }
    }

    public void closeAllDevice(RoomBean roomBean){
        List<DeviceBean> devices = roomBean.getDevices();
        List<Map<String, Object>> list = new ArrayList();
        List<Map<String, Object>> groups = new ArrayList();
        List<DeviceBean> newDeviceBean = new ArrayList();

        for(DeviceBean deviceBean : devices){
            if(deviceBean.getType().equals("light") && !deviceBean.getIsDisable()){
                Map<String, Object> option = new HashMap<>();
                option.put(LLDeviceUtil.POWER, 0);
                Map<String, Object> status = new HashMap<>();
                status.put(LLDeviceUtil.STATUS, option);
                Map<String, Object> deviceItem = new HashMap<>();
                deviceItem.put("stateData", status);
                if(deviceBean.getDeviceGroup() == 0){
                    deviceItem.put("deviceSerialNo", deviceBean.getDeviceSerialNo());
                    list.add(deviceItem);
                    deviceBean.setPower(0);
                    newDeviceBean.add(deviceBean);
                }else{
                    deviceItem.put("deviceGroupSerialNo", deviceBean.getDeviceSerialNo());
                    groups.add(deviceItem);
                }
            }
        }
        LLHttpManager.deviceAllClose(getActivity(), list, new HttpCallback<HttpData<Void>>(null){
            @Override
            public void onStart(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity) {
                    ((AppActivity) getContext()).showDialog("执行中...");
                }
            }

            @Override
            public void onSucceed(HttpData<Void> result) {
                LLDeviceDBManager.getInstance(getContext()).putInTx(newDeviceBean);
            }

            @Override
            public void onFail(Exception e) {
                if(getContext() != null && getContext() instanceof AppActivity) {
                    ToastUtils.show(R.string.exec_failure);
                }
            }

            @Override
            public void onEnd(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity) {
                    ((AppActivity) getContext()).hideDialog();
                }
            }
        });
    }
    
    private void No_equipment() {
        roomRecyclerView.setVisibility(View.GONE);
        roomSmallRecyclerView.setVisibility(View.GONE);
        ll_Noequipment.setVisibility(View.VISIBLE);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                gotoAddRoomActivity(floorSerialNo);
            }
        });
    }

    //当前变化有设备
    private void Ye_sequipment() {
        roomRecyclerView.setVisibility(View.VISIBLE);
        roomSmallRecyclerView.setVisibility(View.VISIBLE);
        ll_Noequipment.setVisibility(View.GONE);
    }

    private void gotoAddRoomActivity(String floorSerialNo){
        Intent intent = new Intent(getContext(), AddRoomActivity.class);
        intent.putExtra("floorSerialNo", floorSerialNo);
        startActivity(intent);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRefreshRoomDeviceEvent(RefreshRoomDeviceEvent event) {
//        rooms = LLRoomDBManager.getInstance(getContext()).getRoomByFloorSerialNo(floorSerialNo);
//        mRoomListBigAdapter.setData(rooms);
//        mRoomListSmallAdapter.setData(rooms);
        initData();
    }

    @Override
    public void onClick(View view) {
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    protected void initData() {
        List<FloorBean> floors = LLFloorDBManager.getInstance(getContext()).getFloorByHouseSerialNo(AppApplication.getInstance().getCurHouseInfo().getHouseSerialNo());
        rooms = LLRoomDBManager.getInstance(getContext()).getRoomByFloorSerialNo(floorSerialNo);
        if(floors.size() == 1){
            RoomBean roomBean = new RoomBean();
            roomBean.setRoomName(floors.get(0).getFloorName());
            roomBean.setPicUrl(floors.get(0).getPicUrl());
            roomBean.setFloorSerialNo(floors.get(0).getFloorSerialNo());
            roomBean.setLinkType(-1);
            rooms.add(0,roomBean);
        }
        if(rooms == null || rooms.size() == 0){
            No_equipment();
        }else{
            Ye_sequipment();
            mRoomListBigAdapter.setData(rooms);
            mRoomListSmallAdapter.setData(rooms);
            setViewShow();
        }
    }


    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }
}
